/**
 * 添加或者修改页面
 */
var IndentOrderInfoDlg = {
    data: {
        indentOrderNum: "",
        dealer: "",
        purchaseId: "",
        time: "",
        checkCode: "",
        remark: ""
    }
};

var check = {
    tableId: "checkTable"
};
layui.use(['form', 'admin', 'ax', 'layedit', 'table', 'tableSelect', 'layer'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var admin = layui.admin;
    var layedit = layui.layedit;
    var lay_table = layui.table;
    var table = layui.table;
    var table_select = layui.tableSelect;
    var layer = layui.layer;

    //让当前iframe弹层高度适应
    admin.iframeAuto();

    var id = $("#indentId").val();
    console.log("传来的id是："+id);

    var Product = {
        tableId: "productTable"
    };

    //表格
    Product.initColumn = function () {
        return [[
            {field: 'id', hide: true, title: '主键'},
            {field: 'productName', sort: false, title: '产品大类'},
            {field: 'productModelName', sort: false, title: '产品型号'},
            {field: 'productOrderName', sort: false, title: '产品品号'},
            {field: 'color', sort: true, title: '产品颜色'},
            {field: 'colorNumber', sort: true, title: '产品色号'},
            {field: 'material', sort: true, title: '产品材质'},
            {field: 'price', sort: true, title: '产品价格'},
            /*{field: 'packageSize', sort: true, title: '包装尺寸'},*/
            {field: 'unitName', sort: true, title: '购买单位'},
            {field: 'orderNumbers', sort: true, title: '购买数量'},
            {field: 'orderAmount', sort: true, title: '总金额'},
            {field: 'havaSend', sort: true, title: '已发'},
            {field: 'notSend', sort: true, title: '未发'},
            {align: 'center', toolbar: '#tableBar', title: '操作'}
        ]];
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + Product.tableId,
        url: Feng.ctxPath + '/purchaseOrders/details?ids='+$("#ids").val()+'&dealer='+$("#dealer").val()+'',
        page: true,
        height: "full-158",
        cellMinWidth: 100,
        cols: Product.initColumn()
    });
    //监听单元格编辑
    lay_table.on('edit(productTable)', function (obj) {
        var value = obj.value; //得到修改后的值
        var data = obj.data;
        obj.update({
            orderAmount: getAmount(data.conversionRatio,data.unitId, data.orderNumbers,data.price)
        });

        lay_table.reload('purchaseDetail', {
            data: lay_table.cache['purchaseDetail']
        });
    });


    lay_table.on('select(productTable)', function (obj) {
        var loding = layer.load(1, {shade: [0.5, '#000']});
        console.log(obj.elem); //得到select原始DOM对象
        console.log(obj.value); //得到被选中的值
        console.log(obj.othis); //得到美化后的DOM对象

        setTimeout(function () {
            var ajax = new $ax(Feng.ctxPath + "/indentOrder/purchaseDetail/" + id);
            lay_table.reload('purchaseDetail', {
                data: ajax.start().data
            });
            layer.close(loding);
        }, 0);


    });



    function getAmount(conversionRatio,unitId, orderNumbers,price) {

        if (!isNaN(conversionRatio) && !isNaN(orderNumbers) && !isNaN(price)) {
            if (unitId ===1){
                return (parseFloat(conversionRatio)*parseFloat(orderNumbers)*parseFloat(price)).toFixed(2);
            }else if (unitId ===2){
                return ( parseFloat(orderNumbers))*parseFloat(price).toFixed(2);
            }
        } else {
            return "0";
        }

    }



    lay_table.on('tool(productTable)', function (obj) {
        var data = obj.data;

        switch (obj.event) {
            case "del":
                layer.confirm('are you 确定?', function (index) {
                    obj.del();
                    layer.close(index);
                });
                break;
            case "remark":
                layer.prompt({
                    formType: 2,
                    value: data.remark,
                    title: '备注',
                    area: ['500px', '200px'] //自定义文本域宽高
                }, function (value, index, elem) {
                    obj.update({
                        remark: value
                    });

                    layer.close(index);
                });
                break;
            case "setUnit":
                layer.open({
                    title: "⚙ 单位选择",
                    type: 2,
                    skin: 'layui-layer-admin',
                    content: Feng.ctxPath + '/unit/unitsByProductId?productId='+data.id, //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
                    area: ['500px', '205px'],
                    end: function (){
                        var unit = admin.getTempData('ok');
                        console.log(unit);
                        console.log(unit.id);
                        obj.update({
                            unitName: unit.name,
                            unitId: unit.id,
                            orderAmount: getAmount(data.conversionRatio,data.unitId,data.orderNumbers,data.price)
                        });
                        console.log(getAmount(data.conversionRatio,data.id, data.orderNumbers,data.price));
                        lay_table.reload('purchaseDetail', {
                            data: lay_table.cache['purchaseDetail']
                        });
                    }, cancel: function () {
                        obj.update({
                            unitsId: data.unitsId,
                            orderAmount: getAmount(data.conversionRatio,data.unitId,data.price, data.orderNumbers)
                        });
                        lay_table.reload('purchaseDetail', {
                            data: lay_table.cache['purchaseDetail']
                        });
                    }
                });
                break;
        }
    });



    //头工具栏事件
    lay_table.on('toolbar(productTable)', function (obj) {
        var data = obj.data;
        var checkStatus = lay_table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'add':
                top.layui.admin.open({
                    type: 2,
                    area: ["1200px", "650px"],
                    title: '产品添加',

                    content: Feng.ctxPath + '/table_select/product_table_select',
                    end: function () {
                        var oldData = lay_table.cache['purchaseDetail'];
                        var list = admin.getTempData('product_list');
                        for (var i = 0; i < list.length; i++) {
                            oldData.push(list[i]);
                        }

                        lay_table.reload('purchaseDetail', {
                            data: oldData
                        });
                    }, cancel: function () {
                        admin.putTempData("product_list", null);
                    }
                });
                break;
            case 'getCheckLength':
                var data = checkStatus.data;
                layer.msg('选中了：' + data.length + ' 个');
                break;
            case 'isAll':
                layer.msg(checkStatus.isAll ? '全选' : '未全选');
                break;
        }
    });


    //审核表格
    check.initColumn = function () {
        return [[
            {field: 'processInstanceId', hide: true, title: '流程id'},
            {field: 'userName', sort: true, title: '审核人'},
            {field: 'deptName', sort: true, title: '审核人部门'},
            {field: 'comment', sort: true, title: '审批意见'},
            {field: 'checkStr', sort: true, title: '审核状态'},
            {field: 'auditTime', sort: true, title: '审核时间'},
            {align: 'center', toolbar: '#tableBar', title: '操作'}
        ]];
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + check.tableId,
        url: Feng.ctxPath + '/checkLogin/indentOrderLogin/'+$("#indentId").val(),
        page: true,
        height: "full-158",
        cellMinWidth: 100,
        cols: check.initColumn()
    });


    //表单提交事件
    form.on('submit(btnSubmit)', function (data) {

        var ajax = new $ax(Feng.ctxPath + "/purchaseOrders/submit", function (data) {
            Feng.success("添加成功!");

            window.location.href = Feng.ctxPath + "/indentOrder";
            //传给上个页面，刷新table用
            admin.putTempData('formOk', true);

            //关掉对话框
            admin.closeThisDialog();
        }, function (data) {
            window.location.href = Feng.ctxPath + "/indentOrder";
            /*Feng.error("添加失败！" + data.responseJSON.message)*/
        });
        var productDetail = lay_table.cache['purchaseDetail'];

        var requestData = [];

        var errorInfo = "";

        /* //数据验证
         productDetail.forEach(function (value, index, array) {
             if (value.orderNumbers === 0) {
                 errorInfo += "产品:" + value.productName + "采购数量为0或未填写 ! \n "
             }
             if (value.unitsId === null) {
                 errorInfo += "产品:" + value.productName + "单位未填写 ! \n "
             }
         });*/

        if (productDetail.length === 0) {
            Feng.error("请添加产品!");
            return false;
        }

        productDetail.forEach(function (val, index, arr) {
            var product = {};
            product.productId = val.id;
            product.unitId = val.unitId;
            product.orderNumbers = val.orderNumbers;
            product.orderAmount = val.orderAmount;
            product.remark = val.remark;
            requestData.push(product);
        });

        console.log(JSON.stringify(requestData));
        data.field['purchaseDetail'] = JSON.stringify(requestData);
        ajax.set(data.field);
        ajax.start();

        return false;

    });

    //返回按钮
    $("#backupPage").click(function () {
        layer.close(index);
        window.location.href = Feng.ctxPath + '/indentOrderCheck'
    });

    //退回按钮
    $("#return").click(function () {
        window.location.href = Feng.ctxPath + '/indentOrderCheck/backIndex?id = '+ $("#indentId").val() + '&taskId=' + $("#taskId").val();
    });

    //审核按钮
    $("#shenhe").click(function () {
        var id = $("#indentId").val();
        var taskId = $("#taskId").val();
        window.location.href =  Feng.ctxPath + '/indentOrderCheck/shenheIndex?indentOrderId=' + $("#indentId").val() + '&taskId=' + $("#taskId").val();  //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']

    });
   /* $("#return").click(function () {
        var id = $("#indentId").val();
        var taskId = $("#taskId").val();
        window.location.href =  Feng.ctxPath + '/indentOrderCheck/shenheIndex?id=' + id + '&taskId=' + taskId; //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']

    })*/

});